<template>
  <el-row class="tree-container">
    <el-col :span="9">
      <div class="box">
        <el-scrollbar>
          <basic-container>
            <el-input class="fill-input"
              placeholder="输入关键字进行过滤"
              v-model="filterName">
            </el-input>
            <el-tree
              :props="props"
              :load="loadNode"
              :expand-on-click-node=false
              @node-click="nodeClick"
              :filter-node-method="filterNode"
              ref="tree"
              lazy
            >
            </el-tree>
          </basic-container>
        </el-scrollbar>
      </div>
    </el-col>
    <el-col :span="15">
      <basic-container>
        <el-button-group>
          <el-button v-hasPermi="['cms:area:add']" type="primary" size="small" icon="el-icon-circle-plus-outline"
                     @click="addChildren">新增下级
          </el-button>
          <el-button v-hasPermi="['cms:area:remove']" type="primary" size="small" icon="el-icon-delete"
                     @click="handleDelete">删除
          </el-button>
          <el-button type="primary" size="small" icon="el-icon-video-play"
                     @click="handleDebug">调试
          </el-button>
        </el-button-group>
      </basic-container>
      <basic-container>
        <el-form ref="elForm" :model="regionForm" :rules="rules" size="medium" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="父级编码" prop="parentId">
                <el-input v-model="regionForm.parentId" placeholder="请输入父区划编码" readonly disabled
                          :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="父级名称" prop="partentName">
                <el-input v-model="regionForm.partentName" placeholder="请输入父区划名称" :maxlength="11" show-word-limit readonly
                          disabled :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="区划编码" prop="code">
                <el-input v-model="regionForm.code" placeholder="请输入区划编码" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="区划名称" prop="name">
                <el-input v-model="regionForm.name" placeholder="请输入区划名称" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="邮政编码" prop="zipCode">
                <el-input v-model="regionForm.zipCode" placeholder="请输入邮政编码" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="区划排序" prop="sort">
                <el-input-number v-model="regionForm.sort" placeholder="请输入区划排序" controls-position="right" :min="0" :style="{width: '100%'}"/>
              </el-form-item>
            </el-col>
          </el-row>





          <el-form-item label="行政等级" prop="type">
            <el-radio-group v-model="regionForm.type" size="medium">
              <el-radio
                v-for="dict in dict.type.area_type"
                :key="dict.value"
                :label="parseInt(dict.value)"
                border
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="区划备注" prop="remarks">
            <el-input v-model="regionForm.remarks" type="textarea" placeholder="请输入备注"
                      :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
          </el-form-item>

          <el-form-item >
            <el-button @click="handleEmpty">清空</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </el-form-item>
        </el-form>
      </basic-container>

     <el-link type="danger" icon="el-icon-info" @click="handSync">同步高德行政区划数据</el-link>
    </el-col>
    <el-dialog title="行政区划数据调试" :visible.sync="debugBox" width="50%" append-to-body>
      <el-form ref="form" :model="casModel"  label-width="80px">
        <el-form-item label="行政区划" prop="name">
          <el-cascader
            style="width: 90%"
            ref="cascaderAddr"
            size="medium"
            v-model="areaArr"
            :options="areaoptions"
            :props="props"
            ></el-cascader>
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-row>

</template>

<script>
import {getLazyTree, getArea, updateArea, addArea, delArea, cascade, gaodeSync} from "@/api/cms/area";
  import {validatenull} from "@/utils/validate";
  export default {
    dicts: ['area_type'],
    data() {
      return {
        filterName: '',
        props: {
          // value: 'id',
          // label: 'name',
          children: 'children',
          isLeaf: 'leaf'
        },
        topCode: '00',
        treeCode: '',
        treeParentCode: '',
        treeData: [],
        regionForm: {
          parentId: 0,
          partentName: '中国',
          code: "",
          name: "",
          zipCode: "",
          sort: 0,
          type: 1
        },
        excelBox: false,
        excelForm: {},
        debugBox: false,
        debugForm: {},
        queryParam: {
          parentId: '0'
        },
        rules: {
          parentId: [
            { required: true, message: "上级行政区划不能为空", trigger: "blur" }
          ],
          code: [
            { required: true, message: "区划编码不能为空", trigger: "blur" }
          ],
          name: [
            { required: true, message: "区划名称不能为空", trigger: "blur" }
          ],
          type: [
            { required: true, message: "区划等级不能为空", trigger: "blur" }
          ],
        },
        areaoptions: [],
        areaArr:[],
        casModel: []
      };
    },
    watch: {
      filterName(val) {
        this.$refs.tree.filter(val);
      }
    },
    created() {
      this.loadCascade();
    },
    methods: {
      loadCascade(){
        cascade().then(res => {
          this.areaoptions = res.data;
        })
      },
      loadNode(node, resolve) {
        console.log(node)
        if (node.level === 0) {
          this.queryParam.parentId = 0
        }
        if (node.level > 0) {
          this.queryParam.parentId = node.data.id
        }
        getLazyTree(this.queryParam).then(res => {
          return resolve(res.data);
        });
      },

      /*树节点点击事件*/
      nodeClick(data, node) {
        getArea(data.id).then(res => {
          this.regionForm = res.data;
          this.regionForm.partentName = node.parent.id ?  node.parent.data.label : '中国'
        })
      },
      /*过滤树节点*/
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      handleEmpty(){
        this.regionForm.parentId = 0;
        this.regionForm.partentName = '中国';
        this.regionForm.code = '';
        this.regionForm.name = '';
        this.regionForm.type = '1';
      },
      /*新增下级*/
      addChildren() {
        this.regionForm.parentId = (!this.regionForm.id || this.regionForm.id === 0) ? 0 : this.regionForm.id;
        this.regionForm.partentName = this.regionForm.parentId === 0 ? '中国' : this.regionForm.name;
        this.regionForm.id = null;
        this.regionForm.code = '';
        this.regionForm.name = '';
        this.regionForm.path = '';
        this.regionForm.sort = '';
        this.regionForm.address = '';
        this.regionForm.zipCode = '';
        this.regionForm.type = (this.regionForm.type === 4 ) ? this.regionForm.type : this.regionForm.type + 1;
      },
      handleSubmit() {
        if (this.regionForm.id){
          updateArea(this.regionForm).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.loadNode()
          }, error => {
            window.console.log(error);
          });
        }else{
          addArea(this.regionForm).then((res) => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.loadNode()
            this.nodeClick(res.data)
          }, error => {
            window.console.log(error);
          });
        }
      },
      handleDelete() {
        if (validatenull(this.regionForm.code)) {
          this.$message.warning("请先选择一项区划");
          return;
        }
        this.$confirm(`确定将 [${this.regionForm.name}] 数据删除?`, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return delArea(this.regionForm.id);
          })
          .then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
        this.loadNode()
      },
      handSync() {
        this.$confirm(`您确定要同步高德行政区划数据吗?如果您的业务已经使用行政区划数据，同步后可能导致错乱！`, {
          confirmButtonText: "确定同步",
          cancelButtonText: "取消同步",
          type: "warning"
        })
          .then(() => {
            return gaodeSync();
          })
          .then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
        this.loadNode()
      },

      handleDebug() {
        this.debugBox = true;
      },
    }
  };
</script>

<style>
  .tree-container{
    margin-top: 10px;
  }
  .box {
    height: 800px;
  }
  .fill-input{
    margin-bottom: 10px;
  }
  .el-scrollbar {
    height: 100%;
  }

  .box .el-scrollbar__wrap {
    overflow: scroll;
  }
</style>
